from flask import Flask, render_template, request
from kubernetes import client, config
from loguru import logger
import requests

# Flask App
app = Flask(__name__)

global_ip = 'http://testbed-master-2'

def get_port(svc: str, port: int, ns: str='default') -> int:
    config.load_incluster_config()
    cl = client.CoreV1Api()
    ret = cl.read_namespaced_service_with_http_info(name=svc, namespace=ns)

    for port_spec in ret[0].spec.ports:
        if port_spec.port == port:
            logger.info(f'Nodeport of {svc}: {port_spec.node_port}')
            return port_spec.node_port

    logger.error(f'Service nodeport not found for {svc}:{port}')
    raise RuntimeError("Service nodeport not found.")


def check_http_url(url: str) -> str:
    if requests.get(url).status_code != 200:
        return '服务中断'
    else:
        return url


svc_port_dict = {
    'kibana (用户名是admin, 密码是123456)': '''f"{global_ip}:{get_port('eck-kb-http', 5601, 'default')}"''',
    'frontend': '''f"{global_ip}:{get_port('ts-ui-dashboard', 8080, 'default')}"''',
    'elasticsearch': '''f"{global_ip}:{get_port('eck-es-http', 9200, 'default')}"''',
    'jaeger调用链网页版http': '''f"{global_ip}:{get_port('jaeger-frontend', 16686, 'default')}"''',
    'chaos-mesh故障注入工具': '''f"{global_ip}:{get_port('chaos-dashboard', 2333, 'chaos-mesh')}"''',
    'jaeger (GRPC)': '''f"{global_ip}:{get_port('jaeger-frontend', 16685, 'default')}"''',
    # 'grafana': '''f"{global_ip}:{get_port('grafana', 3000, 'istio-system')}"''',
    # 'K8s Dashboard': '''check_http_url("https://dashboard.testbed.xz2000.cn/")''',
    # 'Kiali': '''f"{global_ip}:{get_port('kiali', 20001, 'istio-system')}"''',
    # 'Prometheus': '''f"{global_ip}:{get_port('prometheus', 9090, 'istio-system')}"''',
    # 'Proxy': '''f"{global_ip}:{get_port('serviceproxy', 6789, 'default')}"'''
}


@app.route('/')
def view_page():
    # Port of different services
    urls = []

    for k, v in svc_port_dict.items():
        try:
            urls.append((k, eval(v)))
        except Exception as err:
            logger.error(err)
            urls.append((k, '服务中断'))

    return render_template(
        template_name_or_list='index.html',
        urls=urls
    )

if __name__ == '__main__':
    app.run('0.0.0.0', port=6789, debug=True)
